#include <glib.h>

static gint g_option_test(gint argc, gchar **argv)
{
    gboolean ret = -1;
    guint index = 0;
    GError *error = NULL;
    GOptionContext *context = NULL;

    gchar *main_str = NULL;
    gint   main_int = 0;
    gchar *main_file = NULL;
    gdouble main_double = 0.0;
    gint64 main_int64 = 0;
    gboolean main_bool = FALSE;
    gchar **main_array = NULL;
    gchar **main_remain = NULL;

    GOptionEntry main_entries[] = {
        { "string", 's', 0, G_OPTION_ARG_STRING, &main_str, "string type", "S" },
        { "int", 'i', 0, G_OPTION_ARG_INT, &main_int, "int type", "I" },
        { "file", 'f', 0, G_OPTION_ARG_FILENAME, &main_file, NULL, NULL },
        { "double", 'd', 0, G_OPTION_ARG_DOUBLE, &main_double, NULL, NULL },
        { "int64", 'l', 0, G_OPTION_ARG_INT64, &main_int64, NULL, NULL },
        { "bool", 'b', 0, G_OPTION_ARG_NONE, &main_bool, "bool type, -b with no value, no arg", NULL },
        { "array", 'a', 0, G_OPTION_ARG_STRING_ARRAY, &main_array, "array type -a 1, -a 2", NULL },
        { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &main_remain, "Rest goes here", "REST" },
        { NULL }
    };

    if(argc < 2) {
        g_print("Help: %s -h | -? | --help | --help-all \n", argv[0]);
        return -1;
    }

    context = g_option_context_new("< g_option_context_new argument parameter string >");

    g_option_context_set_summary (context, "context summary");
    g_option_context_set_description(context, "context description");

    g_option_context_add_main_entries(context, main_entries, NULL);

    ret = g_option_context_parse(context, &argc, &argv, &error);
    if(TRUE != ret) {
        g_print("option parse failed: %s \n", error->message);
        return -1;
    }

    g_print("main_str: %s \n", main_str);
    g_print("main_int: %d \n", main_int);
    g_print("main_file: %s \n", main_file);
    g_print("main_double: %f \n", main_double);
    g_print("main_int64: %4lld \n", main_int64);
    g_print("main_bool: %s \n", main_bool?"TRUE":"FALSE");

    index = 0;
    while((NULL != main_array) && (NULL != main_array[index]) ) {
        g_print("main_array[%d]: %s \n", index, main_array[index]);
        index ++;
    }
    index = 0;
    while((NULL != main_remain) && (NULL != main_remain[index]) ) {
        g_print("main_remain[%d]: %s \n", index, main_remain[index]);
        index ++;
    }

    g_free(main_str);
    g_free(main_file);
    g_strfreev(main_array);
    g_strfreev(main_remain);

    g_option_context_free (context);

    return 0;
}

gint main(gint argc, gchar **argv)
{
    g_option_test(argc, argv);
    return 0;
}